<?php

/**
 * descript:
 * User: blue
 * Date: 2018/6/5 9:25
 */

namespace app\api\model;

use app\api\service\DeliverMessage;
use app\lib\enum\PayEnum;
use app\lib\exception\OrderException;

class Order extends Base
{
    protected $autoWriteTimestamp = true;

    // public function getSnapItemsAttr($value,$data){
    //     return json($value);
    // }
    /**
     * @param $uid 用户id
     * @param $size 分页大小
     * @param int $page 当前页
     * @return array
     */
    static public function orderPage($uid,$size,$page=1){
        $data=self::where('user_id','=',$uid)
            ->order('create_time desc')
            ->paginate($size,true);
        if($data->isEmpty()){
            return [
                'data'=>[],
                'page'=>1
            ];
        }
        $dataArr=$data->toArray();
        return [
            'data'=>$dataArr,
            'page'=>$data->currentPage()
        ];
    }

    /**
     * @param $uid 用户id
     * @param $orderId 订单编号
     * @return array ['code','data']
     */
    static public function orderInfo($uid,$orderId){
        $data=self::where(['user_id'=>$uid,'id'=>$orderId])->find();
        if(!$data){
            return [
                'code'=>'error',
                'data'=>[]
            ];
        }
        return [
            'code'=>'success',
            'data'=>$data
        ];
    }

    public static function getSummaryByPage($page=1, $size=20){
        $pagingData = self::order('create_time desc')
            ->paginate($size, true, ['page' => $page]);
        return $pagingData ;
    }

    public static function sendDeliverMsg($order_id){
        $data=self::get('$order_id')->find();
        if(!$data){throw new OrderException(['msg'=>'订单不存在']);}
        //更新订单状态为已发货
        $data->status=PayEnum::DELIVERED;
        $data->save();
        return (new DeliverMessage)->deliverMessage($data);
    }
}